package com.coalmine.activiti.flow.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.coalmine.activiti.common.flow.model.FlowTaskComment;
import com.coalmine.activiti.common.flow.service.FlowWorkOrderService;
import com.coalmine.activiti.flow.service.CmFlowApiService;
import com.coalmine.activiti.flow.service.CmFlowService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("cmFlowService")
public class CmFlowServiceImpl implements CmFlowService {

    @Autowired
    private CmFlowApiService cmFlowApiService;
    @Autowired
    private FlowWorkOrderService flowWorkOrderService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewAndStartProcess(
            String processDefinitionId,
            FlowTaskComment flowTaskComment,
            JSONObject taskVariableData,
            String bizId) {

        log.info("参数：{}",processDefinitionId);
        log.info("参数：{}",flowTaskComment.toString());
        log.info("参数：{}",taskVariableData.toJSONString());
        log.info("参数：{}",bizId);
        // 启动流程实例并自动完成第一个用户任务。
        ProcessInstance instance =
                cmFlowApiService.startAndTakeFirst(processDefinitionId, bizId, flowTaskComment, taskVariableData);

        flowWorkOrderService.saveNew(instance, bizId, null, null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateAndTakeTask(
            Task task,
            FlowTaskComment flowTaskComment,
            JSONObject taskVariableData,
            String bizId,
            int flowStatus) {

        // 更新流程状态，同时接收流程任务。
        cmFlowApiService.updateAndTakeTask(task, bizId, flowTaskComment, taskVariableData, flowStatus);
    }

}
